package com.github.ghsea.dbtracer.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RecordLogger {

	private static Logger logger = LoggerFactory.getLogger(RecordLogger.class);

	private static RecordLogger instance = new RecordLogger();

	private static String SQL_INERT = "INSERT INTO db_history_log(original_key,biz_type,biz_name,chang_log,create_time,operator) VALUE (?,?,?,?,?,?)";

	private RecordLogger() {
	}

	public static RecordLogger getInstance() {
		return instance;
	}

	public void logToDB(final Connection conn, DbHistoryLog history) {
		logToDB(conn, Arrays.asList(history));
	}

	public void logToDB(final Connection conn, List<DbHistoryLog> historyList) {
		if (historyList == null || historyList.isEmpty()) {
			return;
		}
		try {
			insert(conn, historyList);
		} catch (Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	private void insert(final Connection conn, List<DbHistoryLog> historyList) throws SQLException {
		PreparedStatement pst = null;
		try {
			pst = conn.prepareStatement(SQL_INERT);
			for (DbHistoryLog history : historyList) {
				pst.setString(1, history.getKey());
				// TODO it's just dummy.FIX ME
				pst.setInt(2, 1);
				pst.setString(3, history.getBizName());

				String changeLog = DbHistoryLogUtil.createChangeLog(history);
				pst.setString(4, changeLog);
				pst.setTimestamp(5, new java.sql.Timestamp(history.getCreateTime().getTime()));
				pst.setString(6, history.getOperator());
				
				pst.addBatch();
				logger.info("Log change history:" + changeLog + ",where=" + history.getWhere());
				logger.info("Log change history vo:" + history);
			}
			pst.executeBatch();
			// pst.executeUpdate();

		} catch (SQLException ex) {
			throw ex;
		} finally {
			try {
				if (null != pst) {
					pst.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

}
